package com.ksana.bean.factory.support;

import com.ksana.bean.factory.DisposableBean;
import com.ksana.bean.factory.config.BeanDefinition;
import com.ksana.util.StringUtil;

import java.lang.reflect.InvocationTargetException;

public class DisposableBeanAdapter implements DisposableBean, Runnable {
    private String beanName;
    private Object bean;
    private BeanDefinition mbd;

    public DisposableBeanAdapter(String beanName, Object bean, BeanDefinition mbd) {
        this.beanName = beanName;
        this.bean = bean;
        this.mbd = mbd;
    }

    @Override
    public void destroy() {
        String destroyMethodName = mbd.getDestroyMethodName();

        if (!StringUtil.isNotEmpty(destroyMethodName)) {
            try {
                mbd.getBean().getMethod(destroyMethodName).invoke(bean);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        destroy();
    }
}
